package com.github_Dididipapa.shortlink.admin.common.biz.user;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {

    private final StringRedisTemplate stringRedisTemplate;
    private final List<String> IGNORE_URI = List.of(
            "/api/short-link/admin/v1/login",
            "/api/short-link/admin/v1/has-username",
            "/api/short-link/admin/v1/title");

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();
        if (IGNORE_URI.contains(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String username = httpServletRequest.getHeader("username");
        String token = httpServletRequest.getHeader("token");
        Object loginJson = stringRedisTemplate.opsForHash().get("login_" + username, token);
        if (loginJson != null) {
            UserInfoDTO userInfoDTO = JSON.parseObject((String) loginJson, UserInfoDTO.class);
            UserContext.setUser(userInfoDTO);
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }
}
